<template>
	
	<el-button plain size="mini" type="primary" @click.stop="getRelation">题目关联</el-button>
	
	<el-dialog v-model="isShow" title="编辑题目关联属性" width="50%" >
		
		<div class="currentQ">当前题目：{{title}}</div>
		<div class="relationQ">关联题目：</div>
			<el-scrollbar max-height="400px">
				<el-cascader
						v-if="value!=null"
						:options="arr"
						:props="props"
						v-model="value"
						size="medium"
						placeholder="请选择关联题目"
						style="width: 70%"
						@change="printf"
						clearable>
					
					<template #default="{ node, data }">
						<span>{{ data.label }}  </span>
						<span v-if="data.type==='checkbox'&&!node.isLeaf">
							[当
							<el-button plain size="mini" @click.stop="changeChoose(data)">{{data.isChoose?"选择":"未选"}}</el-button>
							<el-button plain size="mini" @click.stop="changeAll(data)">{{data.isAll?"全部":"之一"}}</el-button>
							时]
						</span>
						<span v-if="data.type==='radio'&&!node.isLeaf">[当选择之一时]</span>
					</template>
				</el-cascader>
			</el-scrollbar>
			
		
		<template #footer>
		    <span class="dialog-footer">
			    <div style="float:left;margin-bottom: 10px">关联多题时：多题（每个一级菜单视为一题）间
				    <div></div>
				    <el-radio-group v-model="logic">
					    <el-radio label="或">为“或”的关系</el-radio>
					    <el-radio label="且">为“且”的关系</el-radio>
				    </el-radio-group>
				    <div class="note">注：存在题目关联的问卷随机属性将不生效</div>
			    </div>
			    <div style="clear:both;"></div>
			    <div style="float: left">
				    <el-button icon="el-icon-delete" round type="warning" size="small" @click="deleteAll">删除所有题目关联</el-button>
			    </div>
			    <div style="float: right">
				    <el-button @click="isShow = false" >取 消</el-button>
		            <el-button type="primary" @click="submitRelation">提 交</el-button>
			    </div>
			    <div style="clear: both"></div>
		    </span>
		</template>
	</el-dialog>
</template>

<script>
	import axios from "axios";
	import qs from "qs";
	import {ElMessage} from "element-plus";
	
	function relationString(value,questions,logic){
		let data={};
		value.forEach(each=>{
			let key = each[0];
			if(data.hasOwnProperty(key)){
				data[key].add(each[1])
			}else{
				data[key]=new Set([each[1]]);
			}
		});
		let ans = "";
		let length = questions.length;
		questions.every((question,index)=>{
			let key = question.type+"@"+question.id;
			if(data.hasOwnProperty(key)){
				if(ans!=="")ans+=" "+logic+"\n";
				ans+="依赖于["+question.title+"]的选项(";
				question.options.forEach((option,index)=>{
					if(data[key].has(option.id)){
						ans+=option.text+" ";
					}
				});
				ans+=")";
			}
			delete data[key];
			return true;
		});
		return ans;
	}
	
	export default {
		name: "relation",
		props:{
			questionnaireId: Number,
			questionId: Number,
			question: Object,
			type: String,
			questions: Array,
		},
		data(){
			return{
				logic: "且",
				isShow: false,
				props:{multiple: true},
				arr:[],
				value: null,
				title: null,
				relation: null,
				relationString: null,
			}
		},
		methods:{
			// emitString(){
			// 	let data={
			// 		questionId: this.questionId,
			// 		type: this.type,
			// 		relationString: relationString(this.value,this.questions,this.question.logic),
			// 	};
			// 	axios.post("/api/relation/string",qs.stringify(data))
			// 	.then(res=>{
			// 		console.log(res);
			// 		this.question.relationString = res.data.data;
			// 	});
			//
			// 	this.$emit("relation",data.ans);
			// },
			printf(){
				// console.log(this.arr);
				console.log(this.value);
			},
			getRelation(){
				if(this.questions.length===0){
					ElMessage.error('此题目前面无可关联的题目');
					return;
				}
				this.isShow=!this.isShow;
				if(this.isShow){
					this.arr=[];
					this.questions.forEach(question=>{
						this.arr.push(this.question2RelationType(question));
					});
					
					let data={
						questionId: this.questionId,
						type: this.type,
					};
					axios.post("/api/relation/get",qs.stringify(data))
						.then(res=>{
							console.log(res);
							if(res.data.code===0){
								this.initRelation(res.data.data)
							}
						})
				}
			},
			initRelation(data){
				this.title = data.title;
				this.value=data.value;
				
				this.logic = data.logic;
				let map = data.map;
				this.arr.forEach(question=>{
					if(question.type==="checkbox"){
						if(map.hasOwnProperty(question.value)){
							question.isChoose = map[question.value].isChoose;
							question.isAll = map[question.value].isAll;
						}
					}
				})
				
			},
			submitRelation(){
				let data = {
					questionnaireId: this.questionnaireId,
					questionId: this.questionId,
					type: this.type,
					arr: [],
					logic: this.logic,
					relationString: relationString(this.value,this.questions,this.logic)
				};
				this.value.forEach(each=>{
					console.log(each);
					if(each[0].substr(0,1)==="c"){
						this.arr.forEach(item=>{
							if(item.value===each[0]){
								data.arr.push([each[0],each[1],item.isChoose,item.isAll])
							}
						})
					}else{
						data.arr.push(each);
					}
				});
				
				axios.post("/api/relation/submit",data)
				.then(res=>{
					console.log(res);
					if(res.data.code===0){
						ElMessage.success('提交成功');
						this.question.relationString=data.relationString;
						this.isShow = !this.isShow;
					}else{
						ElMessage.error(res.data.msg);
					}
					
				}).catch(err=>{
				
				});
				
				
			},
			deleteAll(){
				this.$confirm('确定删除该问卷所有关联关系？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					axios.post("/api/relation/delete",qs.stringify({
						questionnaireId: this.questionnaireId
					})).then(res=>{
						console.log(res.data.data);
						if(res.data.code===0){
							ElMessage.success('删除成功');
							location.reload();
						}
					});
				});
				
			},
			changeChoose(arg){
				arg.isChoose=!arg.isChoose;
			},
			changeAll(arg){
				arg.isAll=!arg.isAll;
			},
			question2RelationType(item,isChoose=true,isAll=false){
				let question = {};
				question.value = item.type+"@"+item.id;
				question.label = item.title;
				question.type=item.type;
				question.isChoose = isChoose;
				question.isAll = isAll;
				question.children = [];
				console.log(item);
				item.options.forEach(option=>{
					question.children.push(this.option2RelationType(option,question.type));
				});
				return question;
			},
			option2RelationType(item,type){
				let option = {};
				console.log(item);
				option.value = item.id;
				option.label = item.text;
				option.type = type;
				return option;
			},
			
		}
	}
	
	
	
	// relationMap={
	// 	type@id: {
	// 		logic: or/and
	// 		type@id: [] 多选则前两个是isChoose和isAll，单选则是optionId
	// 		type@id: [] 多选则前两个是isChoose和isAll，单选则是optionId
	//      },
	// 	type@id: {
	// 		logic: or/and
	// 		type@id: [] 多选则前两个是isChoose和isAll，单选则是optionId
	// 		type@id: [] 多选则前两个是isChoose和isAll，单选则是optionId
	// 	}
	// }

	// question：{
	// 	calls: [question],
	// 	remind:{
	// 		type@id:{
	// 			isChoose,
	// 			isAll,
	// 			isShow
	// 			type
	// 			optionIds:[]
	// 			relationQuestion:
	//          compute:()
	// 		}
	// 	}
	// }
</script>

<style>
	.el-cascader > .el-cascader__tags >.el-tag {
		font-size: 18px;
		color: #ff7f24;
	}
	.currentQ{
		font-size: 20px;
		font-weight: bold;
		padding-bottom: 10px;
	}
	.relationQ{
		font-size: 20px;
		font-weight: bold;
		padding-bottom: 10px;
	}
	.note{
		font-size: 15px;
		color: red;
		padding-bottom: 5px;
	}
</style>